import { login, getInfo, logout } from '@/api/user'
import { setToken, getToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'
const state = {
  token: getToken(),
  name: '',
  avatar: '',
  introduction: '',
  roles: []
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_INTRODUCTION: (state, introduction) => {
    state.introduction = introduction
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  }
}

const actions = {
  // 退出登录
  logout({ commit, state, dispatch }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(res => {
        commit('SET_TOKEN', '')
        commit('SET_ROLES', [])
        removeToken()
        resetRouter()
        resolve()
      }).catch(err => {
        reject(err)
      })
    })
  },
  // 登录
  login({ commit }, userInfo) {
    // const { username, password } = userInfo
    return new Promise((resovle, reject) => {
      const { username, password } = userInfo
      console.log('data', userInfo)
      login({ username: username.trim(), password: password }).then(response => {
        const { token } = response.data
        commit('SET_TOKEN', token)
        // 将token放置的cookie之中
        setToken(token)
        resovle(token)
      }).catch(err => {
        reject(err)
      })
    })
  },
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token).then(response => {
        const { data } = response
        if (!data) {
          reject('认证失败, 请重新登录')
        }
        // 获取到用户的角色, 姓名, 头像, 简介
        const { roles, name, avatar, introduction } = data
        if (!roles) {
          reject('用户角色不能为空')
        }
        // 将用户信息保存到 state中
        commit('SET_ROLES', roles)
        commit('SET_NAME', name)
        commit('SET_AVATAR', avatar)
        commit('SET_INTRODUCTION', introduction)
        resolve(data)
      }).catch(err => {
        reject(err)
      })
    })
  }
}
export default {
  namespaced: true,
  state,
  mutations,
  actions
}
